<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Changer:  
 * Datetime: 2023年07月18日18:09:54
 */

namespace App\Http\Model;


use App\Http\Services\CommonServices;
use App\Http\Services\UserFilterServices;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use phpDocumentor\Reflection\Types\Self_;

class Ad extends Base
{
    protected $table = "ad";
    protected $giftTable = "gift_library";
    protected $table_ad_push = 'ad_push';
    protected $redis_ad_pop_times  = 'AD:POP:TIMES:';
    protected $redis_ad_plan_activity  = 'AD:PLAN:ACTIVITY';
    protected $user;
    protected $colorGinftModel;
    protected $roomUser;
    public function __construct(array $attributes = [])
    {
        $this->user = new User();
        $this->colorGinftModel = new ColorGift();
        $this->roomUser = new RoomUser();
        parent::__construct($this->table, $attributes);
    }



    /**
     * 获取banner列表手机端
     * @return mixed|null
     * @author  
     */
    public function get_banner($type = 0,$userid=null, $giftIds=[], $roomId=0){
        $time = time();
        //获取用户info
        $userinfo = User::where('user_id',$userid)->first();
        $bannerlist=[];
        $test_user_ids = $this->user->get_test_users();
        if(in_array($userid,$test_user_ids)){
            $bannerlist = $this->get_customer_no_limit($type);
            return  $bannerlist;
        }
        if (!empty($userinfo)){
            //是否是主播
            $unionUser = DB::table('union_user')->where('user_id',$userid)->first();
            $unionUser = self::objToArray($unionUser);
            $usercat = 2;
            if (!empty($unionUser))
            {
                $unionCheck = DB::table('union')->where('id',$unionUser['un_id'])->where('authentication_status','>',0)->exists();
                if($unionCheck){
                    $usercat = 1; //主播
                }
            }
            //获取用户魅力值与财富值
            $userwalletDB = new FinanceUserWallet();
            $userFinanceWalletInfo = $userwalletDB->get_wallet($userid);
            $userCharm = $userFinanceWalletInfo['charm_balance'] ?? 0; //魅力值
            $userBalance = $userFinanceWalletInfo['wealth_balance'] ?? 0;//财富值
            //获取用户充值总金额
            $userRechargeDB = new FinanceRechargeOrder();
            $userRecharge = $userRechargeDB->getRechargeTotal($userid); //充值金额

            if (!empty($userRecharge))
            {
                //转换为钻石数
                $userRecharge = $userRecharge/10;
            }
            //查询满足用户组定制的banner,没有的话就表示查user_Cat为0的的banner
            $where = function($q)use($usercat, $roomId, $type) {
                $q->where('type',$type);
                $q->where('status',0);
                $q->whereIn('user_cat',[$usercat,0]);
            };
            $bannerlist = DB::table($this->table)
                ->where($where)
                ->orderBy('sort','ASC')
                ->get();
            $bannerlist = self::objToArray($bannerlist);
            if(!empty($bannerlist))
            {
                //广告弹窗
                if($type == 10){
                    $times = $this->getPopUpTimes($userid);
                    if($times >=5){
                        return [];
                    }else{
                        $this->setPopUpTimes($userid);
                    }
                }

            }

            /**
             * 展示逻辑
             * 1,banner满足开始时间大于等于当前时间,结束时间小于等于当前日期,若结束时间为空则不做判断
             * 2,banner展示条件满足,用户魅力值在设定的区间AND用户财富值在设定的区间AND用户充值额在设定的区间
             */
            foreach ($bannerlist as $k => $v){
                //1,banner满足开始时间大于等于当前时间,结束时间小于等于当前日期,若结束时间为空则不做判断
                if ($v['start_timestamp'] <= $time && ($v['end_timestamp'] >= $time || empty($v['end_timestamp']) ))
                {
                    //2,banner展示条件满足,用户魅力值在设定的区间AND用户财富值在设定的区间AND用户充值额在设定的区间
                    /**
                     * 1若最小魅力值和最大魅力值都为0的话则不作为判断
                     * 不为0的话则进行值判断
                     * 2 最大财富值或者最小财富值为0的话不作为判断
                     * 不为0的话进行值判断
                     * 3若最小充值金额与最大充值金额为0不判断
                     * 不为0则进行值对比
                     */
                    if ((($userCharm >= $v['mincharm'] && $userCharm <= $v['maxcharm']) || ($v['mincharm']==0 && $v['maxcharm']==0)) &&
                        (($userBalance >= $v['minrich'] && $userBalance <= $v['maxrich']) || ($v['minrich']==0 && $v['maxrich']==0)) && (($userRecharge >= $v['minmoney'] && $userRecharge <= $v['maxmoney']) || ( $v['minmoney']==0 && $v['maxmoney']==0)))
                    {
                        $bannerlist[$k]['img'] = getPicDomain() . $bannerlist[$k]['img'];
                        $bannerlist[$k]['action'] = $v['action']?$v['action']:$v['url'];
                    }else{
                        unset($bannerlist[$k]);
                    }

                }else{
                    unset($bannerlist[$k]);
                }

                //幸运礼物
                if(!empty($giftIds) && isset($bannerlist[$k])) {
                    if(!empty($v['gift_id'])) {
                        if(!in_array($v['gift_id'], $giftIds)) {
                            unset($bannerlist[$k]);
                        }
                    }
                }

                //若存在房间配置则指定房间才展示
                if(!empty($v['room_ids'])){
                    $roomIds = explode(',',$v['room_ids']);
                    if(!in_array($roomId,$roomIds)){
                        unset($bannerlist[$k]);
                    }
                }
                
            }
        }
        return array_values($bannerlist);
    }




    /**
     * 获取广告
     */
    public function get_ad($id){
        $time = time();
        $result = DB::table($this->table)
            ->where(['id' => $id])
            ->first(['id', 'name', 'img', 'url', 'outside', 'auto_time' ,'type','action','desc']);
        if (empty($result)){
            return null;
        }

        $data = self::objToArray($result);
        $data['img'] = getPicDomain() . $data['img'];
        return $data;
    }


    /**
     * 获取自定义配置广告（小屋 ....）
     */
    public function get_customer($type ,$param=[]){
        $condition['status'] = 0;
        $condition['type'] = $type;
        $condition[] = ['start_timestamp', '<', time()];
        $condition[] = ['end_timestamp', '>', time()];
        //增加性别判断
        $genders = array(0);
        if(isset($param['gender'])){
            $genders[] = $param['gender'];
        }
        //增加用户分类判断
        $user_cat = array(0);
        if(isset($param['user_cat'])){
            $user_cat[] = $param['user_cat'];
        }
        $channel_no = $param['channel_no'] ?? '';



        $result = DB::table($this->table)
            ->where($condition)
            ->whereIn('gender',$genders)
            ->whereIn('user_cat',$user_cat)
            ->where(function ($query) use ($channel_no) {
                $query->where('channel_no', 'like', "%{$channel_no}%")->orWhere('channel_no', '=', '');
            })
            ->orderBy('sort', 'asc')
            ->get(['id', 'name', 'img', 'url', 'outside', 'start_timestamp', 'end_timestamp','auto_time','wealth_value','action','desc']);
        if (empty($result)){
            return null;
        }

        $data = self::objToArray($result);
        foreach ($data as $k => $v){
            $data[$k]['img'] = getPicDomain() . $data[$k]['img'];
            $data[$k]['action'] = $v['action']?$v['action']:$v['url'];
        }
        return $data;
    }

    /**添加推送记录
     * @param $ad_id
     * @param $user_ids
     * @param $push_time
     * @param int $status
     * @return mixed
     */
    public function addAdPush($ad_id,$user_ids,$push_time,$status=0){
        $params = array(
            'ad_id'=>$ad_id,
            'user_ids' =>$user_ids,
            'push_time'=>$push_time,
            'status'=>$status
        );
        return DB::table($this->table_ad_push)->insertGetId($params);
    }

    public function getAdPush($id){
        $res = DB::table($this->table_ad_push)->where('is_del', 0)->find($id);
        return $this->objToArray($res);
    }

    public function updateAdPush($id ,$status){
        DB::table($this->table_ad_push)->where('id' ,$id)
            ->update(array('status'=>$status ,'operate_time'=>time()));
    }

    public function delAdPush($pushId){
        return DB::table($this->table_ad_push)
            ->where('id' ,$pushId)
            ->update(array('is_del'=>1 ));
    }

    /**
     * 获取自定义配置广告（小屋 ....）-无限制
     */
    public function get_customer_no_limit($type){
        $condition['type'] = $type;

        $result = DB::table($this->table)
            ->where($condition)
            ->orderBy('sort', 'asc')
            ->get(['id', 'name', 'img', 'url', 'outside', 'auto_time','wealth_value','action','desc']);
        if (empty($result)){
            return null;
        }

        $data = self::objToArray($result);
        foreach ($data as $k => $v){
            $data[$k]['img'] = getPicDomain() . $data[$k]['img'];
            $data[$k]['action'] = $v['action']?$v['action']:$v['url'];
        }
        return $data;
    }

    /**获取广告弹窗每日弹出次数
     * @param $user_id
     * @return mixed
     */
    public function getPopUpTimes($user_id){
        return Redis::Hget($this->redis_ad_pop_times.date('Ymd') ,$user_id);
    }

    /**设置广告弹窗每日弹出次数
     * @param $user_id
     */
    public function setPopUpTimes($user_id){
        $key = $this->redis_ad_pop_times.date('Ymd') ;
        Redis::HINCRBY($this->redis_ad_pop_times.date('Ymd') ,$user_id ,1);

        if (Redis::TTL($key) == -1) {
            Redis::EXPIRE($key, 1 * 24 * 3600);
        }
    }

    /**
     * 根据条件获取banner
     *
     * @param mixed $conditions
     * @return array|mixed
     */
    public function getBannersByConditions($conditions)
    {
        $result = DB::table($this->table)
            ->where($conditions)
            ->orderBy('sort', 'asc')
            ->get();
        if (empty($result)){
            return [];
        }

        $data = self::objToArray($result);
        foreach ($data as $k => $v){
            $data[$k]['img'] = getPicDomain() . $v['img'];
            $data[$k]['icon'] =  $v['icon'] ? getPicDomain() . $v['icon'] : '';
        }

        return $data;
    }


    //礼物banner
    public function getGiftBanner($list, $userId)
    {
        $result = [];
        if(!empty($list)) {
            $giftIds = array_column($list, 'goods_id');
            $ad = $this->get_banner(11, $userId, $giftIds);
            if(!empty($ad)) {
                $ad = array_column($ad, null, 'gift_id');
            }

            foreach($list as $val) {
                if($val['goods_type'] == 1){
                    if(isset($ad[$val['goods_id']])) {
                        $val['gift_banner'] = $ad[$val['goods_id']];
                        //套盒礼物
                        if(isset($val['gift_type']) && $val['gift_type']==6) {
                            if(!empty($val['ext_data'])) {
                                $ext_data = json_decode($val['ext_data'], true);
                                if(!empty($ext_data)) {
                                    $extGiftList = DB::table($this->giftTable)->whereIn('gift_id',$ext_data)->select(['gift_id','name','image','price'])->get();
                                    $extGiftList = array_column(self::objToArray($extGiftList), null, 'gift_id');
                                    foreach($ext_data as $extVal) {
                                        if(empty($extGiftList[$extVal])) {
                                            continue;
                                        }
                                        $extGiftList[$extVal]['image'] = build_image($extGiftList[$extVal]['image']);
                                        $val['gift_banner']['banner_gift'][] = $extGiftList[$extVal];
                                    }
                                }
                            }
                        }
                    }
                }
                //彩蛋礼物banner不走Ad广告配置
                if($val['gift_type'] == 5){
                    $colorGiftPoolInfo = $this->colorGinftModel->getColorGiftRateBannerByGiftId($val['goods_id']);
                    if(!empty($colorGiftPoolInfo)){
                        $banner = [
                            'id' => $colorGiftPoolInfo['id'],
                            'img' => build_image($colorGiftPoolInfo['img_url']),
                            'action' => $colorGiftPoolInfo['jump_url']
                        ];
                        $val['gift_banner'] = $banner;
                    }
                }
                $result[] = $val;
            }
        }

        return $result;
    }

}
